<template>
  <div>
    <n-space style="margin-bottom:12px">
      <n-text>任务ID: {{ taskId }}</n-text>
      <n-button type="primary" @click="load" :loading="loading" size="small">刷新</n-button>
      <n-switch v-model:value="errorsOnly" @update:value="load">
        <template #checked>仅错误</template>
        <template #unchecked>全部</template>
      </n-switch>
    </n-space>
    
    <n-data-table
      :columns="columns"
      :data="logs"
      :loading="loading"
      :pagination="paginationProps"
      size="small"
      :scroll-x="1200"
    />

    <!-- 消息详情对话框 -->
    <n-modal v-model:show="detailShow" preset="card" title="消息详情" style="width:800px">
      <n-descriptions :column="1" bordered size="small">
        <n-descriptions-item label="时间">{{ selectedMessage?.timestamp }}</n-descriptions-item>
        <n-descriptions-item label="方向">{{ selectedMessage?.direction }}</n-descriptions-item>
        <n-descriptions-item label="源">{{ selectedMessage?.source }}</n-descriptions-item>
        <n-descriptions-item label="目标">{{ selectedMessage?.target }}</n-descriptions-item>
        <n-descriptions-item label="状态">
          <n-tag :type="selectedMessage?.success ? 'success' : 'error'" size="small">
            {{ selectedMessage?.success ? '成功' : '失败' }}
          </n-tag>
        </n-descriptions-item>
        <n-descriptions-item v-if="selectedMessage?.errorMessage" label="错误信息">
          <n-text type="error">{{ selectedMessage.errorMessage }}</n-text>
        </n-descriptions-item>
      </n-descriptions>

      <n-divider>消息内容</n-divider>
      <n-spin :show="loadingDetail">
        <n-code
          :code="messageDetail || selectedMessage?.messagePreview || '无内容'"
          :language="detectLanguage(messageDetail || selectedMessage?.messagePreview || '')"
          show-line-numbers
          style="max-height: 400px; overflow-y: auto;"
          :hljs="hljs"
        />
      </n-spin>
    </n-modal>
  </div>
</template>
<script setup lang="ts">
import { h, ref, onMounted, watch, computed } from 'vue'
import axios from 'axios'
import { NButton, NSpace, NText, NSwitch, NDataTable, NTag, NTime, NTooltip, NModal, NDescriptions, NDescriptionsItem, NDivider, NCode, NSpin, useMessage } from 'naive-ui'
import hljs from 'highlight.js/lib/core'
import javascript from 'highlight.js/lib/languages/javascript'
import json from 'highlight.js/lib/languages/json'
import xml from 'highlight.js/lib/languages/xml'
import plaintext from 'highlight.js/lib/languages/plaintext'

// 注册语言
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('json', json)
hljs.registerLanguage('xml', xml)
hljs.registerLanguage('plaintext', plaintext)
hljs.registerLanguage('text', plaintext)

const props = defineProps<{ taskId: number | null }>()
const message = useMessage()
const loading = ref(false)
const loadingDetail = ref(false)
const errorsOnly = ref(false)
const logs = ref<any[]>([])
const detailShow = ref(false)
const selectedMessage = ref<any>(null)
const messageDetail = ref<string>('')
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

const paginationProps = computed(() => ({
  page: pagination.value.page,
  pageSize: pagination.value.pageSize,
  itemCount: pagination.value.itemCount,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  showQuickJumper: true,
  prefix: ({ itemCount }: any) => `共 ${itemCount} 条`,
  onUpdatePage: handlePageChange,
  onUpdatePageSize: handlePageSizeChange
}))

const columns = [
  { 
    title: '时间', 
    key: 'timestamp', 
    width: 160,
    render: (row: any) => h(NTime, { time: new Date(row.timestamp), format: 'MM-dd HH:mm:ss.SSS' })
  },
  { 
    title: '级别', 
    key: 'level', 
    width: 80,
    render: (row: any) => h(NTag, { 
      type: row.level === 'ERROR' ? 'error' : (row.level === 'WARN' ? 'warning' : 'info'),
      size: 'small'
    }, { default: () => row.level })
  },
  { 
    title: '方向', 
    key: 'direction', 
    width: 120,
    render: (row: any) => row.direction
  },
  { 
    title: '源', 
    key: 'source', 
    width: 150,
    ellipsis: { tooltip: true },
    render: (row: any) => row.source
  },
  { 
    title: '目标', 
    key: 'target', 
    width: 150,
    ellipsis: { tooltip: true },
    render: (row: any) => row.target
  },
  {
    title: '消息预览',
    key: 'messagePreview',
    width: 300,
    ellipsis: { tooltip: true },
    render: (row: any) => {
      const preview = row.messagePreview || '-'
      return h('div', {
        style: 'font-family: monospace; font-size: 12px; max-width: 280px; word-break: break-all; cursor: pointer;',
        onClick: () => showMessageDetail(row)
      }, [
        preview,
        preview !== '-' ? h('span', { style: 'color: #1890ff; margin-left: 8px;' }, '[查看详情]') : null
      ])
    }
  },
  { 
    title: '状态', 
    key: 'success', 
    width: 80,
    render: (row: any) => h(NTag, { 
      type: row.success ? 'success' : 'error',
      size: 'small'
    }, { default: () => row.success ? '成功' : '失败' })
  },
  { 
    title: '错误', 
    key: 'errorMessage', 
    width: 200,
    ellipsis: { tooltip: true },
    render: (row: any) => row.errorMessage || '-'
  }
]

async function load() {
  if (props.taskId == null) return
  
  loading.value = true
  try {
    const endpoint = errorsOnly.value ? `/api/logs/${props.taskId}/errors` : `/api/logs/${props.taskId}`
    const { data } = await axios.get(endpoint, {
      params: {
        page: pagination.value.page - 1,
        size: pagination.value.pageSize
      }
    })
    
    logs.value = data.content
    pagination.value.itemCount = data.totalElements
    
    if (data.content.length > 0) {
      message.success(`加载了 ${data.content.length} 条日志`)
    }
  } catch (e) {
    message.error('加载日志失败')
    console.error(e)
  } finally {
    loading.value = false
  }
}

function handlePageChange(page: number) {
  pagination.value.page = page
  load()
}

function handlePageSizeChange(pageSize: number) {
  pagination.value.pageSize = pageSize
  pagination.value.page = 1 // 重置到第一页
  load()
}

async function showMessageDetail(message: any) {
  selectedMessage.value = message
  messageDetail.value = ''
  detailShow.value = true

  // 获取完整消息内容
  if (message.id) {
    loadingDetail.value = true
    try {
      const { data } = await axios.get(`/api/logs/message/${message.id}`)
      messageDetail.value = data.fullMessageContent
    } catch (e) {
      console.error('Failed to load message detail:', e)
      messageDetail.value = '加载消息详情失败'
    } finally {
      loadingDetail.value = false
    }
  }
}

function detectLanguage(content: string): string {
  if (!content) return 'text'

  const trimmed = content.trim()
  if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
    return 'json'
  }
  if (trimmed.startsWith('<')) {
    return 'xml'
  }
  if (trimmed.startsWith('[HEX]')) {
    return 'plaintext'
  }
  return 'text'
}

watch(() => props.taskId, (newId) => {
  if (newId != null) {
    pagination.value.page = 1
    load()
  }
}, { immediate: true })
</script>
